package com.xpp.servcie;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xpp.dao.UserDao;
import com.xpp.pojo.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Override//这个String s会接收表中传来username时会自动
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //调用userDao方法，根据用户名查询数据库
        QueryWrapper<MyUser> wrapper=new QueryWrapper<>();
        wrapper.eq("name", s);
        MyUser user=userDao.selectOne(wrapper);
        if(user==null){
            throw new UsernameNotFoundException("你妈妈找你吃饭");
        }
        //设置权限  给查询出来的数据赋予admins权限
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("admins");
        return new User(user.getName(), new BCryptPasswordEncoder()
                .encode(user.getPassword()), role);
    }

}
